#include "chatwidget.h"
#include "ui_chatwidget.h"
#include "components/chatbubble.h"
#include "components/useritem.h"
#include "components/clientsocket.h"
#include <QMessageBox>
#include <QTimer>
#include <QFile>

ChatWidget::ChatWidget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::ChatWidget)
{
    ui->setupUi(this);
    heart_beat_timer = new QTimer(this);
    connectAllSlots();
}

ChatWidget::~ChatWidget()
{
    delete ui;
}

void ChatWidget::setCurrentUserName(const QString &current_user_name)
{
    this->current_user_name = current_user_name;
    ui->label_2->setText(current_user_name);
}

void ChatWidget::fileRead(const QJsonObject &obj)
{
    QString fileName = obj["file_name"].toString();
    if(obj.contains("total_size")){
        if(recv_file.file_name == fileName && recv_file.total_size){
            recv_file.data.append(QByteArray::fromBase64(obj["data"].toString().toUtf8()));
            if(recv_file.data.size() == obj["total_size"].toInt()){
                QFile file(fileName);
                if (file.open(QIODevice::WriteOnly)) {
                    file.write(recv_file.data);
                    QMessageBox::information(this, "传输", "文件传输成功");
                    file.close();
                } else {
                    QMessageBox::critical(this, "传输", "文件传输失败");
                }
                recv_file.clear();
            }
        }else{
            recv_file.clear();
            recv_file.total_size = obj["total_size"].toInt();
            recv_file.file_name = fileName;
            recv_file.data = QByteArray::fromBase64(obj["data"].toString().toUtf8());
        }
    }else{
        QByteArray fileData = QByteArray::fromBase64(obj["data"].toString().toUtf8());
        QFile file(fileName);
        if (file.open(QIODevice::WriteOnly)) {
            file.write(fileData);
            QMessageBox::information(this, "传输", "文件传输成功");
            file.close();
        } else {
            QMessageBox::critical(this, "传输", "文件传输失败");
        }
    }
}

void ChatWidget::setFriendList(const QJsonObject &friend_list)
{
    QHBoxLayout *layout = (QHBoxLayout *)ui->scrollAreaWidgetContents_2->layout();
    while (layout->count() != 1)
    {
        QLayoutItem* item = layout->takeAt(0);
        if (QWidget* widget = item->widget())
            widget->deleteLater();
        delete item;
    }
    QJsonArray user_list = friend_list.value("friend_status").toArray();
    for (int i = 0; i < user_list.count(); i++) {
        QJsonObject user = user_list.at(i).toObject();
        QString user_name = user.value("user_name").toString();
        QString user_status = user.value("user_status").toString();
        UserItem *item = new UserItem;
        ui->widget->addFriend(user_name);
        item->setUserName(user_name);
        connect(item,&UserItem::changeUserName,[=](){
            ui->user_name->setText(user_name);
            ui->widget->changeChatPage(user_name);
            send_user_name = user_name;
        });
        if(user_status == "live")
            item->setOnLine();
        else
            item->setOutLine();
        layout->insertWidget(layout->count() - 1,item);
    }
}

void ChatWidget::receive(const QJsonObject &sendMessage)
{
    QString send_user = sendMessage.value("send_user").toString();
    QString message=sendMessage.value("send_message").toString();
    ui->widget->appendMessageTo(send_user,message,Qt::AlignLeft);
}

void ChatWidget::connectAllSlots()
{
    // 计时器定时发送获取好友列表状态请求
    connect(heart_beat_timer,&QTimer::timeout,this,[&](){
        if(!client->isConnected()){
            QMessageBox::critical(this,"网络异常","网络连接断开");
            return ;
        }
        client->friendListQuery();
    });
    // 绑定好友列表回复与设置好友列表信号槽
    connect(client,&ClientSocket::friendListReply,this,&ChatWidget::setFriendList);
    connect(client,&ClientSocket::recvSecretChat,this,&ChatWidget::receive);
    connect(heart_beat_timer,&QTimer::timeout,this,[=](){
        if(client->isConnected() == false){
            QMessageBox::critical(this,"网络异常","网络连接断开");
            return ;
        }
        client->friendListQuery();
    });
    connect(client,&ClientSocket::fileRead,this,&ChatWidget::fileRead);
}

void ChatWidget::showEvent(QShowEvent *e)
{
    // 启动定时器
    heart_beat_timer->start(5000);
    //发送一次获取好友列表请求
    if(!client->isConnected()){
        QMessageBox::critical(this, "网络异常", "网络连接断开");
        return ;
    }
    client->friendListQuery();
    QWidget::showEvent(e);
}

void ChatWidget::on_pushButton_3_clicked()
{
    //打开文件的目录
    QString filePath = QFileDialog::getOpenFileName(this, "选择文件", "./");
    if(filePath == "") return;
    QFile file(filePath);
    file.open(QIODevice::ReadOnly);
    client->sendFile(send_user_name,file);
}

void ChatWidget::on_send_btn_clicked()
{
    QString message = ui->textEdit->toPlainText();
    ui->widget->appendMessage(message,Qt::AlignRight);
    client->secretChat(send_user_name,message);
    ui->textEdit->clear();
}

